package com.yuanchu.common.utils;

import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;

import java.io.Serializable;
import java.util.List;

/**
 * @version: 1.0
 * @Author: adan
 * @description:
 * @date: 2024-01-26 14:37
 */
@Data
public class PageResult<T> implements Serializable {

    // 总条数
    private Integer total;
    // 每页显示条数
    @JsonProperty("per_page")
    private Integer perPage;

    // 当前页
    @JsonProperty("current_page")
    private Integer currentPage;

    // 分页数
    @JsonProperty("last_page")
    private Integer lastPage;

    private List<T> data;
    public static <T> PageResult<T> formatPageResult(List<T> records, int page, int perPage) {

        long total = records.size();
        PageResult<T> result = new PageResult<>();

        result.setTotal((int) total);
        result.setCurrentPage(page);
        result.setData(records);
        result.setPerPage(perPage);

        // 计算总页数，向下取整避免超出实际页数
        int totalPages = (int) Math.ceil((double) total / perPage);
        result.setLastPage(totalPages);

        return result;
    }
    public static <T> PageResult<T> formatPageResult(List<T> records, int page, int perPage, long total) {

        PageResult<T> result = new PageResult<>();
        result.setTotal((int) total);
        result.setCurrentPage(page);
        result.setData(records);
        result.setPerPage(perPage);

        // 计算总页数，向下取整避免超出实际页数
        int totalPages = (int) Math.ceil((double) total / perPage);
        result.setLastPage(totalPages);

        return result;
    }
}
